package com.gupao.vip.netty;

import cn.hutool.core.convert.Convert;
import com.gupao.vip.bio.Constants;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.util.Objects;

public class TimeServer {
    public void bind(int port) throws Exception{
        //配置服务端的NIO线程组
        /**
         * NioEventLoopGroup是个线程组
         * 包含了一组NIO线程，专门用于网络事件的处理，实际上它们就是Reactor线程组
         * bossGroup：用于服务端接收客户端的连接
         * workerGroup：用于进行SocketChannel的网路读写
         */
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try{
            //Netty用于启动NIO服务端的辅助启动类，目的是降低服务端的开发复杂度
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    //设置创建的Channel为NioServerSocketChannel，它的功能对于JDK NIO类库中的ServerSocketChannel类
                    .channel(NioServerSocketChannel.class)
                    //配置NioServerSocketChannel的TCP参数，讲它的backlog设置为1024
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    /**
                     * 绑定I/O事件的处理类ChildChannelHandler
                     * 作用类似于Reactor模式中的handler类，主要用于处理网络I/O事件，例如记录日志、对消息进行编解码等
                     */
                    .childHandler(new ChildChannelHandler());

            //绑定端口，同步等待成功
            ChannelFuture f = b.bind(port).sync();

            //等待服务端监听端口关闭
            f.channel().closeFuture().sync();
        }finally{
            //优雅退出，释放线程池资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        int port = Constants.DEFAULT_PORT;
        if(Objects.nonNull(args) && args.length > 0){
            port = Convert.toInt(args[0], Constants.DEFAULT_PORT);
        }
        try {
            new TimeServer().bind(port);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
